<?php
namespace app\admin\controller;

/**
 * 文件上传类
 */
class Upload extends Base
{
	public $picUrl = '';
    public $size = 2 * 1048576;
    public $allowarray = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'doc', 'docx', 'pdf', 'tif', 'xml', 'dotm', 'docm', 'dotx', 'dot', 'xlsx', 'xlsm', 'xltx', 'xltm', 'xlsb', 'xlam', 'pptx', 'pptm', 'ppsx', 'potx', 'potm', 'ppam', 'xls', 'gz', 'mp4', 'mp3'];

    public function init()
    {
        $request = $this->request;
        $this->picUrl = $request->domain();
    }

    /**
     * 单文件上传
     * 上传至本地服务器
     */
    public function upFile()
    {
        $request = $this->request;
        $file = $request->file('file');
        if ($file) {
            $this->init();

            //验证上传文件名称(含后缀)
            $localFileName = $file->getInfo('name');
            $allowNameAry = explode('.', $localFileName);
            $allowName = $allowNameAry[1];       //获取文件后缀

            //验证上传文件类型
            if ($this->allow($allowName) == false) {
                returnJson(0, '不允许上传的文件类型');
            }
            //验证文件大小
            if ($file->getSize() > $this->size) {
                returnJson(0, '文件字节数过大');
            }

            $fileRootPath = PUBLIC_PATH;
            $filePathTemp = "/uploads/" . date("Y") . "/" . date("m") . "/";      //构建文件存储路径
            $fileName = time() . $this->GetRandStr(5) . '.' . $allowName;                   //文件重命名

            $info = $file->move($fileRootPath . $filePathTemp, $fileName);
            if ($info) {
                $data = [
                    'picurl' => '/public' . $filePathTemp . $fileName
                ];

                returnJson(1, '文件上传成功', $data);
            } else {
                returnJson(0, $file->getError());
            }
        }
        returnJson(0, '文件上传失败');
    }

    /**
     * 验证文件后缀名
     * @param string $allowName
     * @return bool
     */
    public function allow(string $allowName): bool
    {
        $allowArray = $this->allowarray;
        if (in_array(strtolower($allowName), $allowArray)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 随机创建文件名
     * @param int $len
     * @return string
     */
    public function GetRandStr(int $len): string
    {
        $chars = array(
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $charsLen = count($chars) - 1;
        shuffle($chars);
        $output = '';
        for ($i = 0; $i < $len; $i++) {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }

}
